package com.demo.websocket.config;

import java.util.concurrent.CopyOnWriteArraySet;

import org.springframework.util.Assert;

import com.demo.websocket.domain.UserClient;

/**
 * Created by baiguantao on 2017/8/4. 用户session记录类
 */
public class SocketSessionRegistry {
	// 这个集合存储session和用户
	private final CopyOnWriteArraySet<UserClient> userSessionIds = new CopyOnWriteArraySet<UserClient>();

	public SocketSessionRegistry() {
	}

	/**
	 *
	 * 获取sessionId
	 * 
	 * @param user
	 * @return
	 * @return
	 * @return
	 */
	public UserClient getSessionIds(String name) {
		for (UserClient userClient : userSessionIds) {
			if (name.equals(userClient.getName())) {
				return userClient;
			}
		}
		return null;
	}

	/**
	 * 获取所有session
	 * 
	 * @return
	 */
	public CopyOnWriteArraySet<UserClient> getAllSessionIds() {
		return this.userSessionIds;
	}

	public void registerSessionId(String name, String sessionId) {
		Assert.notNull(name, "User must not be null");
		Assert.notNull(sessionId, "Session ID must not be null");
		UserClient u = new UserClient(sessionId, name);
		synchronized (this) {
			if (!userSessionIds.contains(u)) {
				for (UserClient userClient : userSessionIds) {
					if (name.equals(userClient.getName())) {
						userClient.setSessionId(sessionId);
						System.err.println("update:"+userClient);
						return;
					}
				}
				this.userSessionIds.add(u);
				System.err.println("add:"+u);
			}
		}
	}

	public void unregisterSessionId(String sessionId) {
		// Assert.notNull(name, "User must not be null");
		Assert.notNull(sessionId, "Session ID must not be null");
		synchronized (this) {
			for (UserClient userClient : userSessionIds) {
				if (sessionId.equals(userClient.getSessionId())) {
					userClient.setSessionId(sessionId);
					userSessionIds.remove(userClient);
					System.err.println("remove:"+userClient);
				}
			}
		}
	}
}
